<template>
  <div class="search-container">
    <van-search class="inputsearch"
                v-model="searchText"
                shape="round"
                background="#d75f95"
                placeholder="请输入搜索关键词"
                clearable
                @search="onSearch"
                show-action
                autofocus>
      <template #action>
        <div @click="onSearch" class="btn-search" size="mini">搜索</div>
      </template>
    </van-search>
    <div class="cancels"><van-icon color="#fff" name="revoke" @click="$router.go(-1)" size="23" /></div>
    <search-result v-if="isResultShow" :searchText="searchText" ref="searchResultRef"></search-result>
    <van-grid v-if="gridShow" :gutter="30" column-num="3" direction="horizontal">
      <span v-if="search.length!=0">搜索历史</span>
      <van-grid-item class="channel-item"
                     v-for="(value,i) in search"
                     :key="i"
                     :text="value"
                     @click="resetinput(value)">
        <template #default>
          <a>{{value}}</a>
          <van-icon name="clear" @click="deleteItem(value)" size="17" />
        </template>
      </van-grid-item>
    </van-grid>
  </div>
</template>

<script>
import SearchResult from './components/SearchResult'
import { mapState } from 'vuex'
export default {
  name: 'SearchIndex',
  components: {
    SearchResult
  },
  data () {
    return {
      searchText: '',
      isResultShow: false,
      gridShow: true
    }
  },
  computed: {
    ...mapState(['search'])
  },
  methods: {
    onSearch () {
      this.gridShow = false
      if (this.searchText.trim().length > 0) {
        this.isResultShow = true
        setTimeout(() => {
          if (this.$refs.searchResultRef.isShow) {
            this.gridShow = true
          }
          this.$refs.searchResultRef.onLoad()
          this.$store.commit('addsearch', this.searchText.trim())
        }, 100)
      } else {
        this.$toast.fail('请输入内容')
      }
    },
    deleteItem (val) {
      this.$store.commit('removesearch', val)
    },
    resetinput (val) {
      this.searchText = val
    }
  }
}
</script>

<style scoped lang="less">
  .van-search {
    .btn-search

  {
    width: 70px;
    color: #fff;
  }

  .van-search__action {
    border-radius: 16px;
    &:active

  {
    background-color: #d75f95;
  }

  }
  }
  .cancels{
    position:fixed;
    top:20px;
    left:25px;
  }
  .van-search {
    border-bottom: 1px solid #808080;
    box-shadow: 1px 1px 3px 3px #e3e3e3
  }
  .inputsearch{
      padding-left:90px;
  }
  .van-grid {
    margin-top: 50px;
    position: relative;
    color: #808080;
    span{
          font-size:20px;
          position:absolute;
          top:-40px;
          width:20%;
          left:10px;
        }
  .van-grid-item {
    height: 50px;
  }
  a {
    font-size: 20px;
  }
  .van-icon{
    position:relative;
    right:-20px;
  }
  }
</style>
